package com.cloudeasy.api.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

/**
 * Json工具
 */
public class JsonUtil {
    /**
     * {@link ObjectMapper}
     */
    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 对象转Json
     *
     * @param o {@link Object} 对象
     * @return Json字符串
     */
    public static String toJson(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Json转对象
     *
     * @param json      Json字符串
     * @param classType {@link Class<T>}目标类型
     * @param <T>       结果泛型
     * @return {@link T}
     */
    public static <T> T fromJson(String json, Class<T> classType) {
        try {
            return objectMapper.readValue(json, classType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
